package com.tao.plan.controller;


import cn.hutool.core.bean.BeanUtil;
import com.tao.plan.common.BaseThreadLocal;
import com.tao.plan.common.R;
import com.tao.plan.common.utils.DateUtil;
import com.tao.plan.domain.pojo.PCountDownDay;
import com.tao.plan.domain.pojo.PMemoryDay;
import com.tao.plan.domain.vo.AllDayVo;
import com.tao.plan.domain.vo.MemoryDayVo;
import com.tao.plan.service.PCountDownDayService;
import com.tao.plan.service.PMemoryDayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/memoryDay")
public class MemoryDayController {
	@Autowired
	private PMemoryDayService pMemoryDayService;
	@Autowired
	private PCountDownDayService pCountDownDayService;
	/**
	 * 新增
	 */
	@PostMapping("/add")
	public R add(@RequestBody PMemoryDay memoryDay){
		memoryDay.setUid(Long.valueOf(BaseThreadLocal.getUid()));
		pMemoryDayService.save(memoryDay);
		return R.build().success();
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	public R update(@RequestBody PMemoryDay memoryDay){
		pMemoryDayService.updateById(memoryDay);
		return R.build().success();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/delete/{id}")
	public R delete(@PathVariable("id") Long id){
		pMemoryDayService.removeById(id);
		return R.build().success();
	}

	/**
	 * 根据类型查询
	 */
	@GetMapping("/listByType/{type}")
	public R listByType(@PathVariable("type") Integer type){
		List<PMemoryDay> list = pMemoryDayService.listByType(type);
		List<MemoryDayVo> collect = list.stream().map(item -> {
			MemoryDayVo memoryDayVo = new MemoryDayVo();
			BeanUtil.copyProperties(item, memoryDayVo);
			LocalDateTime targetTime = item.getTargetTime();
			memoryDayVo.setFirstDays(Long.valueOf(DateUtil.getFirstDays(targetTime,item.getType() != 0)));
			memoryDayVo.setNextDays(Long.valueOf(DateUtil.getNextDays(targetTime,item.getType() != 0)));
			return memoryDayVo;
		}).collect(Collectors.toList());
		return R.build().success().put("data",collect);
	}
	/**
	 * 根据传入的日期进行查询, 纪念日和倒计时
	 * 公历和农历都要查询
	 */
	@GetMapping("/listByDay")
	public R listByDay(@RequestParam("lunar") String lunar, @RequestParam("calendar") String calendar){
		List<PMemoryDay> memoryDays = pMemoryDayService.listByDay(lunar,calendar);
		List<PCountDownDay> countDownDays = pCountDownDayService.listByDay(calendar);
		// 调整返回格式
		List<AllDayVo> list = new ArrayList<>();
		memoryDays.forEach(item->{
			AllDayVo allDayVo = new AllDayVo();
			BeanUtil.copyProperties(item,allDayVo);
			allDayVo.setMemoryDay(true);
			list.add(allDayVo);
		});
		countDownDays.forEach(item->{
			AllDayVo allDayVo = new AllDayVo();
			BeanUtil.copyProperties(item,allDayVo);
			allDayVo.setType(0);
			allDayVo.setMemoryDay(false);
			list.add(allDayVo);
		});
		return R.build().success().put("data",list);
	}

}
